package 字符串算法;

import java.util.HashMap;

public class 字符串转整数 {

    public static void main(String[] args) {
        String aChar = "-91283472332";
        solution solution = new solution();
        int i = solution.myAtoi(aChar);
        System.out.println(i);
    }

}

class solution{
 public int myAtoi(String str){

     int len = str.length();
     auto auto = new auto();
     for (int i=0;i<len;i++){
         char c = str.charAt(i);
         auto.get(c);
     }
     return (int)(auto.sign*auto.anx);
 }
}

class auto{
    public int sign = 1;
    public long anx = 0;
    public String state = "start";
    private HashMap<String,String[]> table = new HashMap<String, String[]>(){
        {
            put("start",new String[]{"start","signed","num","end"});
            put("signed",new String[]{"end","end","num","end"});
            put("num",new String[]{"end","end","num","end"});
            put("end",new String[]{"end","end","end","end"});
        }
    };
    public void get(char c){
        state = table.get(state)[getoc(c)];
        if ("num".equals(state)){
            anx = anx * 10 + c - '0';
            anx = sign == 1 ?Math.min(anx,(long)Integer.MAX_VALUE):Math.min(anx,-(long)Integer.MIN_VALUE);
        }else if("signed".equals(state)){
            sign = c == '+'?1:-1;
        }

    }
    public int getoc(char c){
        if (c==' '){return 0;}
        if (c=='+'||c=='-'){return 1;}
        if (Character.isDigit(c)){return 2;}
        return 3;
    }
}